<?php
/**
 * 鉴权中间件
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);

namespace app\admin\middleware;

use app\admin\exception\AdminServiceException;
use app\admin\service\AdminAuthService;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AdminLoginCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $url = get_request_url();

        $request->request_url = $url;

        $url_lower    = strtolower($url);
        $except_lower = array_map('strtolower', ADMIN_LOGIN_EXCEPT);

        // 需要验证登录
        if (!in_array($url_lower, $except_lower, false)) {
            // TODO::针对不同的请求返回不同的类型，html/json
            try {
                $request->user = (new AdminAuthService)->getAdminUserAuthInfo();

            } catch (AdminServiceException $e) {

                $redirect  = $url . '';
                $login_url = '/admin/auth/login?redirect=' . $redirect;

                return $request->method() === 'GET' ? redirect($login_url) : admin_error($e->getMessage(), $login_url);
            }
        }

        return $handler($request);
    }
}